const initialState = {
  articleData: {} as IArticleDataMap,
  detail: {} as IDetail,
};

export type ActionType =
  | { type: 'article/saveList'; payload: { channel_id: number; article: IArticleData } }
  | {
      type: 'article/updateList';
      payload: { channel_id: number; article: IArticleData };
    }
  | { type: 'article/saveDetial'; payload: IDetail };

function articleReducer(state = initialState, action: ActionType): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      return {
        ...state,
        articleData: {
          ...state.articleData,
          [action.payload.channel_id]: action.payload.article,
        },
      };

    case 'article/updateList':
      const preResults = state.articleData[action.payload.channel_id].results;
      const newResultes = [...preResults, ...action.payload.article.results];
      return {
        ...state,
        articleData: {
          ...state.articleData,
          [action.payload.channel_id]: {
            results: newResultes,
            pre_timestamp: action.payload.article.pre_timestamp,
          },
        },
      };

    case 'article/saveDetial':
      return {
        ...state,
        detail: action.payload,
      };

    default:
      return state;
  }
}

export default articleReducer;

interface IArticleDataMap {
  [key: number]: IArticleData;
}

interface IArticleData {
  results: IArticle[];
  pre_timestamp: string;
}

export interface IArticle {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: ICover;
}

interface ICover {
  type: number;
  images?: string[];
}

export interface IDetail {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
}
